package com.zyh.server.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zyh.server.config.Constant;
import com.zyh.server.utils.RedisUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @Author: zyh
 * @Date: 2024-11-14-8:46
 * @Description 系统拦截器
 */
@Slf4j
@Component
public class SysInterceptor implements HandlerInterceptor {
	@Autowired
	private RedisUtil redisUtil;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 获取请求路径
		String uri = request.getRequestURI();
		log.info("拦截的请求路径是:{}", uri);
		// 判断是否是拦截器方法
		if (handler instanceof HandlerMethod){
			// 判断请求头中token是否为null
			String token = request.getHeader("token");
			log.info("token的值是:{}", token);
			if (StrUtil.isEmpty(token)){
				// token为空就抛出异常
				log.error("本次请求token为空");
				throw new RuntimeException("token为空，请求失败");
			}else {
				// token不为空，判断本次请求的token是否在redis中
				Object obj = redisUtil.getObj(Constant.REDIS_TOKEN_PREFIX + token);
				// 判断从redis中获取的token是否为空
				if (Objects.isNull(obj)){
					// 为空说明token不在redis中，也就是请求的token已经失效
					log.error("本次请求的token已经失效");
					throw new RuntimeException("token已经失效，请求失败");
				}else {
					// token不为空，并且redis中有，就放行
					return true;
				}
			}
		}
		return true;
	}
}
